package com.itjin.health.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itjin.health.common.BaseResponse;
import com.itjin.health.common.ResultUtils;
import com.itjin.health.domain.dto.UserApprovalRequest;
import com.itjin.health.domain.dto.UserUpdateRequest;
import com.itjin.health.domain.vo.UserVO;
import com.itjin.health.exception.BusinessException;
import com.itjin.health.exception.ErrorCode;
import com.itjin.health.service.AdminService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin")
@Api(tags = "管理员接口")
@Slf4j
public class AdminController {

  @Resource
  private AdminService adminService;

  /**
   * 分页获取用户列表
   *
   * @param current 当前页
   * @param size    每页大小
   * @param role    角色筛选（可选）
   * @param keyword 搜索关键词（可选，匹配用户名或学号）
   * @param request HTTP请求
   * @return 用户列表
   */
  @GetMapping("/user/list")
  @ApiOperation(value = "分页获取用户列表")
  public BaseResponse<Page<UserVO>> listUsers(
      @RequestParam(defaultValue = "1") long current,
      @RequestParam(defaultValue = "10") long size,
      @RequestParam(required = false) String role,
      @RequestParam(required = false) String keyword,
      HttpServletRequest request) {
    // 校验管理员权限
    checkAdminPermission(request);
    Page<UserVO> userPage = adminService.listUsersByPage(current, size, role, keyword);
    return ResultUtils.success(userPage);
  }

  /**
   * 获取待审核的管理员和教师账号列表
   *
   * @param request HTTP请求
   * @return 待审核账号列表
   */
  @GetMapping("/user/pending")
  @ApiOperation(value = "获取待审核的管理员和教师账号列表")
  public BaseResponse<List<UserVO>> getPendingAccounts(HttpServletRequest request) {
    // 校验超级管理员权限
    checkSuperAdminPermission(request);
    List<UserVO> pendingList = adminService.getPendingAccounts();
    return ResultUtils.success(pendingList);
  }

  /**
   * 审核用户账号
   *
   * @param approvalRequest 审核请求
   * @param request         HTTP请求
   * @return 审核结果
   */
  @PostMapping("/user/approve")
  @ApiOperation(value = "审核用户账号")
  public BaseResponse<Boolean> approveUserAccount(
      @RequestBody UserApprovalRequest approvalRequest,
      HttpServletRequest request) {
    // 校验超级管理员权限
    checkSuperAdminPermission(request);
    if (approvalRequest == null || approvalRequest.getUserId() == null) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }
    boolean result = adminService.approveUserAccount(approvalRequest);
    return ResultUtils.success(result);
  }

  /**
   * 更新用户信息
   *
   * @param updateRequest 更新请求
   * @param request       HTTP请求
   * @return 更新结果
   */
  @PostMapping("/user/update")
  @ApiOperation(value = "更新用户信息")
  public BaseResponse<Boolean> updateUser(
      @RequestBody UserUpdateRequest updateRequest,
      HttpServletRequest request) {
    // 校验管理员权限
    checkAdminPermission(request);
    if (updateRequest == null || updateRequest.getUserId() == null) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }
    boolean result = adminService.updateUser(updateRequest);
    return ResultUtils.success(result);
  }

  /**
   * 删除用户
   *
   * @param userId  用户ID
   * @param request HTTP请求
   * @return 删除结果
   */
  @PostMapping("/user/delete")
  @ApiOperation(value = "删除用户")
  public BaseResponse<Boolean> deleteUser(
      @RequestParam Integer userId,
      HttpServletRequest request) {
    // 校验管理员权限
    checkAdminPermission(request);
    if (userId == null || userId <= 0) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }
    boolean result = adminService.deleteUser(userId);
    return ResultUtils.success(result);
  }

  /**
   * 重置用户密码
   *
   * @param userId  用户ID
   * @param request HTTP请求
   * @return 重置结果和新密码
   */
  @PostMapping("/user/reset-password")
  @ApiOperation(value = "重置用户密码")
  public BaseResponse<String> resetUserPassword(
      @RequestParam Integer userId,
      HttpServletRequest request) {
    // 校验管理员权限
    checkAdminPermission(request);
    if (userId == null || userId <= 0) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }
    String newPassword = adminService.resetUserPassword(userId);
    return ResultUtils.success(newPassword);
  }

  // ============================= 教师专用接口 =============================

  /**
   * 教师查看学生列表
   *
   * @param current 当前页
   * @param size    每页大小
   * @param keyword 搜索关键词（可选，匹配用户名或学号）
   * @param request HTTP请求
   * @return 学生列表
   */
  @GetMapping("/teacher/student/list")
  @ApiOperation(value = "教师查看学生列表")
  public BaseResponse<Page<UserVO>> listStudentsForTeacher(
      @RequestParam(defaultValue = "1") @ApiParam("当前页") long current,
      @RequestParam(defaultValue = "10") @ApiParam("每页大小") long size,
      @RequestParam(required = false) @ApiParam("关键词") String keyword,
      HttpServletRequest request) {
    // 校验教师权限
    checkTeacherPermission(request);
    // 只查询学生角色的用户
    Page<UserVO> studentPage = adminService.listUsersByPage(current, size, "学生", keyword);
    return ResultUtils.success(studentPage);
  }

  /**
   * 教师更新学生信息
   *
   * @param updateRequest 更新请求
   * @param request       HTTP请求
   * @return 更新结果
   */
  @PostMapping("/teacher/student/update")
  @ApiOperation(value = "教师更新学生信息")
  public BaseResponse<Boolean> updateStudentByTeacher(
      @RequestBody UserUpdateRequest updateRequest,
      HttpServletRequest request) {
    // 校验教师权限
    checkTeacherPermission(request);
    if (updateRequest == null || updateRequest.getUserId() == null) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }

    // 验证是否为学生用户
    boolean isStudent = adminService.checkUserRole(updateRequest.getUserId(), "学生");
    if (!isStudent) {
      throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "教师只能修改学生用户信息");
    }

    // 防止修改用户角色
    if (updateRequest.getRole() != null && !"学生".equals(updateRequest.getRole())) {
      throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "不能修改学生角色");
    }

    boolean result = adminService.updateUser(updateRequest);
    return ResultUtils.success(result);
  }

  /**
   * 教师删除学生账户
   *
   * @param userId  用户ID
   * @param request HTTP请求
   * @return 删除结果
   */
  @PostMapping("/teacher/student/delete")
  @ApiOperation(value = "教师删除学生账户")
  public BaseResponse<Boolean> deleteStudentByTeacher(
      @RequestParam @ApiParam("学生用户ID") Integer userId,
      HttpServletRequest request) {
    // 校验教师权限
    checkTeacherPermission(request);
    if (userId == null || userId <= 0) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }

    // 验证是否为学生用户
    boolean isStudent = adminService.checkUserRole(userId, "学生");
    if (!isStudent) {
      throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "教师只能删除学生账户");
    }

    boolean result = adminService.deleteUser(userId);
    return ResultUtils.success(result);
  }

  /**
   * 教师重置学生密码
   *
   * @param userId  用户ID
   * @param request HTTP请求
   * @return 重置结果和新密码
   */
  @PostMapping("/teacher/student/reset-password")
  @ApiOperation(value = "教师重置学生密码")
  public BaseResponse<String> resetStudentPasswordByTeacher(
      @RequestParam @ApiParam("学生用户ID") Integer userId,
      HttpServletRequest request) {
    // 校验教师权限
    checkTeacherPermission(request);
    if (userId == null || userId <= 0) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }

    // 验证是否为学生用户
    boolean isStudent = adminService.checkUserRole(userId, "学生");
    if (!isStudent) {
      throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "教师只能重置学生密码");
    }

    String newPassword = adminService.resetUserPassword(userId);
    return ResultUtils.success(newPassword);
  }

  /**
   * 校验管理员权限
   *
   * @param request HTTP请求
   */
  private void checkAdminPermission(HttpServletRequest request) {
    Object userObj = request.getSession().getAttribute("userId");
    if (userObj == null) {
      throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
    }
    Integer userId = (Integer) userObj;
    boolean hasPermission = adminService.isAdmin(userId);
    if (!hasPermission) {
      throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
    }
  }

  /**
   * 校验超级管理员权限
   *
   * @param request HTTP请求
   */
  private void checkSuperAdminPermission(HttpServletRequest request) {
    Object userObj = request.getSession().getAttribute("userId");
    if (userObj == null) {
      throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
    }
    Integer userId = (Integer) userObj;
    boolean hasPermission = adminService.isSuperAdmin(userId);
    if (!hasPermission) {
      throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "需要超级管理员权限");
    }
  }

  /**
   * 校验教师权限
   *
   * @param request HTTP请求
   */
  private void checkTeacherPermission(HttpServletRequest request) {
    Object userObj = request.getSession().getAttribute("userId");
    if (userObj == null) {
      throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
    }
    Integer userId = (Integer) userObj;
    boolean hasPermission = adminService.isTeacher(userId);
    if (!hasPermission) {
      throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "需要教师权限");
    }
  }

  @GetMapping("/dashboard/summary")
  @ApiOperation(value = "控制台概览数据（管理员/教师）")
  public BaseResponse<Map<String, Object>> getDashboardSummary(HttpServletRequest request) {
    // 校验权限（管理员或教师均可）
    Object userObj = request.getSession().getAttribute("userId");
    if (userObj == null) {
      throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
    }
    Integer userId = (Integer) userObj;
    boolean isAdminOrTeacher = adminService.isAdmin(userId) || adminService.isTeacher(userId);
    if (!isAdminOrTeacher) {
      throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "需要管理员或教师权限");
    }

    Map<String, Object> summary = adminService.getDashboardSummary();
    return ResultUtils.success(summary);
  }
}
